<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>Ruby Quirks: Ruby Study Notes - Best Ruby Guide, Ruby Tutorial</title>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />
<meta name="description" content="Ruby Study Notes - Best Ruby Guide, Ruby Tutorial" />
<meta name="keywords" content="ruby study notes,ruby quirks,ruby guide,free ruby programming course,best ruby guide,ruby tutorials,ruby tutorial,learn ruby,ruby,ruby on rails,ruby rails,ruby learning,ruby tutoring,learning ruby,ruby programming,ruby on rails development,ruby training" />
<meta name="Distribution" content="Global" />
<meta name="author" content="Satish Talim / Original design: Erwin Aligam - ealigam@gmail.com" />
<meta name="copyright" content="Satish Talim 2007 and beyond..." />
<meta name="verify-v1" content="rFu86se+IkbtF+bH8mgJBKwU5HnKaSd8Ghw9umXQOkM=" />
<meta name="robots" content="index,follow" />
<meta http-equiv="Expires" content="0" />
<meta name="revisit-after" content="1 days" />
<link rel="stylesheet" href="/images/NewOrange.css" type="text/css" />
<link rel="stylesheet" href="/images/syntaxhighlighter.css" type="text/css" />
<!-- Google Analytics code -->
<script type="text/javascript">

  var _gaq = _gaq || [];
  _gaq.push(['_setAccount', 'UA-59044-10']);
  _gaq.push(['_trackPageview']);

  (function() {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
  })();

</script>
<!-- Google Analytics code ends -->
</head>

<body>
<!-- wrap starts here -->
<div id="wrap">

    <div id="header">

        <h1 id="logo">Ruby<span class="orange">Learning.github.io</span></h1>
        <h2 id="slogan">Ruby helps programmers have more fun!</h2>

    </div>

    <div id="menu">
        <ul>
            <li><a href="/" title="Home page for rubylearning.github.io">Home</a></li>
            <li id="current"><a href="/satishtalim/tutorial.html" title="Get started Learning Ruby here...">Tutorial</a></li>
            <li><a href="/download/downloads.html" title="Download this tutorial as an eBook">Downloads</a></li>
            <li><a href="/other/testimonials.html" title="People around the world who benefited from this site">Testimonials</a></li>
            <li><a href="/other/ruby_gurus.html" title="Interviews I took of Ruby Gurus around the world">Gurus</a></li>
            <li><a href="/other/certification.html" title="Get certified in Ruby">Certification</a></li>
            <li><a href="/satishtalim/ruby_guide.html" title="Ruby Guide, Mentor">Mentor</a></li>
            <li><a href="/other/ruby_video_search.html" title="Watch videos on Ruby/Rails">Videos</a></li>
            <li><a href="/blog/" title="Ruby blog of Learning Ruby site">Blog</a></li>
            <li><a href="/satishtalim/tutorial.html" title="Online Ruby Course">Online Course</a></li>
            <li><a href="/satishtalim/about.html" title="Information about Satish Talim">About</a></li>
        </ul>
    </div>

    <!-- content-wrap starts here -->
    <div id="content-wrap">

            <div id="main">

                <div id="main-inner"> <a name="TemplateInfo"></a>
                <h1>Ruby Quirks</h1>

                <p>Ruby Quirks - peculiarity of behavior? I know this topic is debatable and remember 'one man's meat is another man's poison!</p>

                <p>I plan to write down here (in no particular order), some of the little Ruby quirks that I've picked up and which, I now use comfortably.</p>

                <p><strong>1</strong>. Peter Cooper, the author of the book, '<em>Beginning Ruby</em>' introduced me to Real-Time chat using an IRC client. On the #ruby channel at irc://irc.freenode.net/ I heard of this quirk:</p>

                <div class="column2">
                <!-- InstanceBeginEditable name="Code" -->
                <textarea name="code" class="ruby:nogutter:nocontrols" rows="15" cols="60">
                class MotorCycle
                  def initialize(make, color)
                    @make, @color = make, color
                  end
                end

                m = MotorCycle.new('Honda', 'blue')
                m.instance_variable_set(:@make, 'Kawasaki')
                m.instance_variable_set(:@gears, 4)
                puts m.inspect
                </textarea>
                <!-- InstanceEndEditable -->
                </div>

                <p>Check the output of the above program. In the code above,</p>

                <div class="column2">
                <!-- InstanceBeginEditable name="Code" -->
                <textarea name="code" class="ruby:nogutter:nocontrols" rows="15" cols="60">
                m.instance_variable_set(:@gears, 4)
                </textarea>
                <!-- InstanceEndEditable -->
                </div>

                <p>sets the instance variable names by <i>symbol</i> to object, thereby frustrating the efforts of the class's author to attempt to provide proper encapsulation. The variable did not have to exist prior to this call.<br /><strong><span style="color:red;">Update:</span></strong> Hal Fulton in his excellent book 'The Ruby Way' has this to say about instance_variable_set:</p>

                <blockquote><p>It's true these methods are powerful and potentially dangerous. They should be used cautiously, not casually. But it's impossible to say whether encapsulation is violated without looking at <i>how these tools are used</i>. If they are used intentionally as part of a good design, then all is well. If they are used to violate the design, or to circumvent a bad design, then all is not well.</p></blockquote>

                <p><strong>2</strong>. This one is not really a quirk but appears to be one, especially for people coming from a Java background. Last year, <a href="/blog/2007/04/11/interview-shashank-date/" >Shashank Date</a> gave the <a href="http://tech.groups.yahoo.com/group/puneruby/" >PuneRuby</a> members a presentation on 'Why Ruby Shines' and three points stood out - 'Expressions everywhere', 'Active Class Definitions' and 'Everything is an Object'.</p>

                <p><i><strong><small>Expressions everywhere</small></strong></i> - In Ruby, everything returns some value. Therefore a class definition is an expression and one can say something like:</p>

                <div class="column2">
                <!-- InstanceBeginEditable name="Code" -->
                <textarea name="code" class="ruby:nogutter:nocontrols" rows="15" cols="60">
                c = class C
                end
                </textarea>
                <!-- InstanceEndEditable -->
                </div>

                <p>The value of c is nil.</p>

                <p><i><strong><small>Active Class Definitions</small></strong></i> - Look at the following program:</p>

                <div class="column2">
                <!-- InstanceBeginEditable name="Code" -->
                <textarea name="code" class="ruby:nogutter:nocontrols" rows="15" cols="60">
                class C
                  puts 'In class C'
                end
                </textarea>
                <!-- InstanceEndEditable -->
                </div>

                <p>When this class is read the first time, it executes puts and the output is - 'In class C'.</p>

                <p><i><strong><small>Everything is an Object</small></strong></i> - After being with Java since 1995, the concept that classes in Ruby are first-class objects, is hard to digest at first - each is an instance of class Class. When a new class is defined (typically using class Name ... end), an object of type Class is created and assigned to a constant (Name. in this case). Hal Fulton's suggests a <i>mantra</i> to be recited everyday - "Class <i>is an object</i>, and Object <i>is a class</i>."</p>

                <p><strong>3</strong>. If I want to swap two variables, I would normally use an additional temporary variable. In Ruby, this is not necessary:</p>

                <div class="column2">
                <!-- InstanceBeginEditable name="Code" -->
                <textarea name="code" class="ruby:nogutter:nocontrols" rows="15" cols="60">
                x, y = y, x
                </textarea>
                <!-- InstanceEndEditable -->
                </div>

                <p>will interchange the values of x and y.</p>

                <p><strong>4</strong>. Jaaron, a reader of the <a href ="/blog/2007/04/11/ruby-quirks/" >Learning Ruby Blog</a> has this quirk for us. This one is well known and is the cause of much frustration.</p>

                <div class="column2">
                <!-- InstanceBeginEditable name="Code" -->
                <textarea name="code" class="ruby:nogutter:nocontrols" rows="15" cols="60">
                x = 7
                [1,2,3].each do |x|
                end
                </textarea>
                <!-- InstanceEndEditable -->
                </div>

                <p>If the name of a block parameter conflicts with the name of a local variable, the behavior is to assign the local variable to the argument. In this case, the local variable x gets assigned the value 1, then the value 2, then the value 3. The value 7 is lost.</p>

                <p>If you refer to Programming Ruby Second Edition eBook (page 99) it says:</p>

                <blockquote><p>The while, until, and for loops are built into the language and do not introduce new scope; previously existing locals can be used in the loop, and any new locals created will be available afterward.<br /><br />The blocks used by iterators (such as loop and each) are a little different. Normally, the local variables created in these blocks are not accessible outside the block.<br /><br />However, if at the time the block executes a local variable already exists with the same name as that of a variable in the block, the existing local variable will be used in the block. Its value will therefore be available after the block finishes.<br /><br />The whole issue with variable scope and blocks is one that generates considerable discussion in the Ruby community. The current scheme has definite problems (particularly when variables are unexpectedly aliased inside blocks), but at the same time no one has managed to come up with something that's both better and acceptable to the wider community. Matz is promising changes in Ruby 2.0.</p></blockquote>

                <p><strong>5</strong>. Are instance variables inherited by a sub-class? David Black, the author of <em>Ruby for Rails</em> has this to say: Instance variables are per-object, not per-class, and <span class="underline">they're not inherited</span>. But if a method uses one, and that method is available to subclasses, then it will still use the variable -- but "the variable" in the sense of one per object. See the following program:</p>

                <div class="column2">
                <!-- InstanceBeginEditable name="Code" -->
                <textarea name="code" class="ruby:nogutter:nocontrols" rows="15" cols="60">
                class C
                  def initialize
                    @n = 100
                  end

                  def increase_n
                    @n *= 20
                  end
                end

                class D &lt; C
                  def show_n
                    puts "n is #{@n}"
                  end
                end

                d = D.new
                d.increase_n
                d.show_n
                </textarea>
                <!-- InstanceEndEditable -->
                </div>

                <p>The output is:</p>

                <div class="column2">
                <!-- InstanceBeginEditable name="Code" -->
                <textarea name="code" class="ruby:nogutter:nocontrols" rows="15" cols="60">
                >ruby p049instvarinherit.rb
                n is 2000
                >Exit code: 0
                </textarea>
                <!-- InstanceEndEditable -->
                </div>

                <p><strong>6</strong>. Morgan Schweers, a reader of the <a href ="/blog/2007/04/11/ruby-quirks/" >Learning Ruby Blog</a> has this quirk for us. Imagine for a moment, that you want to be able to set a variable, but if it's not set, you default to a known value. You'd rather do it on a single line.<br /><br />One of my co-workers tried this:</p>

                <div class="column2">
                <!-- InstanceBeginEditable name="Code" -->
                <textarea name="code" class="ruby:nogutter:nocontrols" rows="15" cols="60">
                expand = defined?( expand ) ? expand : true
                </textarea>
                <!-- InstanceEndEditable -->
                </div>

                <p>but 'expand' is *defined* by being on the left hand side, BEFORE the RHS is evaluated, so defined? returns true, but because expand hasn't got a value yet, it returns nil.<br /><br />I tried:</p>

                <div class="column2">
                <!-- InstanceBeginEditable name="Code" -->
                <textarea name="code" class="ruby:nogutter:nocontrols" rows="15" cols="60">
                expand = true unless defined?(expand)
                </textarea>
                <!-- InstanceEndEditable -->
                </div>

                <p>and it doesn't help either, which really shocked me. I always believed that the postfix-conditional was evaluated before even beginning to evaluate the operation, but I was distinctly disabused of this notion by testing.<br /><br />Note that 'defined?' operator returns nil if its argument (which can be an arbitrary expression) is not defined; otherwise it returns a description of that argument.<br /><br />I don't understand the reason for the behavior, and I think it's a bug, but I'd love to know a good language reason for it.</p>

                <p><a href="http://zenpax.com/">Kip</a>, a reader writes in with this answer: Here is a work-around using the defined? method:</p>

                <div class="column2">
                <!-- InstanceBeginEditable name="Code" -->
                <textarea name="code" class="ruby:nogutter:nocontrols" rows="15" cols="60">
                if !defined?(expand) then; expand = true; end
                </textarea>
                <!-- InstanceEndEditable -->
                </div>

                <p>However, there is probably a much better way to accomplish this:</p>

                <div class="column2">
                <!-- InstanceBeginEditable name="Code" -->
                <textarea name="code" class="ruby:nogutter:nocontrols" rows="15" cols="60">
                expand = expand || true
                </textarea>
                <!-- InstanceEndEditable -->
                </div>

                <p>And Ruby even has a shortcut for that:</p>

                <div class="column2">
                <!-- InstanceBeginEditable name="Code" -->
                <textarea name="code" class="ruby:nogutter:nocontrols" rows="15" cols="60">
                expand ||= true
                </textarea>
                <!-- InstanceEndEditable -->
                </div>

                <p>Anyway, just thought I'd share that (even though my guess is that you already knew this).</p>

                <p><br />I am sure that you would have noticed many other Ruby quirks. I'd definitely like to hear and add them here.</p>

                <p class="post-footer align-right">
                  <strong>
                    <a href="http://sitekreator.com/satishtalim/solutions.html">&lt;Solutions | </a>
                    <a href="/satishtalim/tutorial.html">TOC | </a>
                    <a href="/satishtalim/ruby_activerecord_and_mysql.html">Ruby ActiveRecord and MySQL&gt;</a>
                  </strong>
                </p>

            </div>
            <!-- main inner ends here -->
        </div>

            <div id="rightbar">
            </div>

    <!-- content-wrap ends here -->
    </div>

<!-- wrap ends here -->
</div>

<!-- footer starts here -->
<div id="footer">
    <!-- CHANGE THE FOOTER -->

    <p>&copy; 2006-2021 <strong>rubylearning.github.io - A Ruby Tutorial</strong>&nbsp;&nbsp;Page Updated: 5th Jan. 2021 | Design: <a href="mailto:ealigam@gmail.com">Erwin Aligam</a> | Valid: <a href="http://validator.w3.org/check/referer">XHTML</a> | <a href="http://jigsaw.w3.org/css-validator/check/referer">CSS</a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href="/">Home</a> | <a href="/privacy.html">Privacy</a> | <a href="/sitemap.html">Sitemap</a></p>
</div>

<!-- footer ends here -->

<!-- SyntaxHighlighter code -->
<script src="/js/shCore.js" type="text/javascript"></script>
<script src="/js/shBrushRuby.js" type="text/javascript"></script>
<script type="text/javascript">
dp.SyntaxHighlighter.HighlightAll('code');
</script>
<!-- SyntaxHighlighter code -->


</body>
</html>
